<template>
  <ToolbarButton type="dropdown" title="字符统计" hideText>
    <template #default>
      {{ totalCharacters }} 字符
    </template>
    <template #dropdown>
      <ul class="character-statistics-menu">
        <li class="menu-header">文档统计信息</li>
        <DropdownItem>
          <div class="stat-item">
            <span class="stat-label">已输入字数:</span>
            <span class="stat-value">{{ inputCharacters }} 字符</span>
          </div>
        </DropdownItem>
        <DropdownItem>
          <div class="stat-item">
            <span class="stat-label">已选中字数:</span>
            <span class="stat-value">{{ selectedCharacters }} 字符</span>
          </div>
        </DropdownItem>
      </ul>
    </template>
  </ToolbarButton>
</template>

<script setup lang="ts">
import { inject, computed, watch, type Ref } from "vue";
import type { Editor } from "@tiptap/vue-3";
import ToolbarButton from "../../button/index.vue";
import { DropdownItem } from "../../dropdown";

defineOptions({
  name: "CharacterContainer",
});

// 注入编辑器实例
const editor = inject<Ref<Editor>>("editor");

// 计算已输入字符数（总字符数）
const inputCharacters = computed(() => {
  if (!editor?.value) return 0;
  return editor.value.storage?.characterCount?.characters() || 0;
});

// 计算已选中字符数
const selectedCharacters = computed(() => {
  if (!editor?.value) return 0;
  const { state } = editor.value;
  const { selection } = state;
  
  if (selection.empty) {
    return 0;
  }
  
  // 获取选中文本的长度
  const selectedText = state.doc.textBetween(selection.from, selection.to);
  return selectedText.length;
});

// 总字符数（显示在按钮上）
const totalCharacters = computed(() => {
  return inputCharacters.value;
});

// 监听编辑器选择和内容更新以实时更新统计
watch(
  () => editor?.value?.state?.selection,
  () => {
    // 当选择改变时，computed 会自动更新
  },
  { deep: true }
);
</script>

<style scoped lang="scss">
.character-statistics-menu {
  list-style: none;
  margin: 0;
  padding: 0;
  min-width: 200px;
}

.menu-header {
  padding: 8px 16px;
  font-size: var(--editor-font-size-small, 12px);
  font-weight: 500;
  color: var(--editor-text-color-secondary, var(--editor-text-color));
  border-bottom: 1px solid var(--editor-border-color-light, var(--editor-border-color));
  margin-bottom: 4px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 4px 0;
}

.stat-label {
  font-size: var(--editor-font-size-small, 12px);
  color: var(--editor-text-color-secondary, var(--editor-text-color));
}

.stat-value {
  font-size: var(--editor-font-size-small, 12px);
  font-weight: 500;
  color: var(--editor-text-color);
}
</style>
